package reduce.fz.com.reduce.photo;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.activity.BaseToolBarActivity;
import reduce.fz.com.reduce.adapter.PhotoWallAdapter;
import reduce.fz.com.reduce.constant.PublishParams;
import reduce.fz.com.reduce.util.ImageCompressUtil;
import reduce.fz.com.reduce.util.ImageSaveUtil;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.Utils;
import reduce.fz.com.reduce.util.base.ReduceApplication;


/**
 * 选择图片页面，以图片墙形式展开
 * 兼容单选多选模式
 * getIntExtra(MAX_SELECT_COUNT) 设置最多选择照片数，默认1
 * getStringExtra(NEXT_ACTIVITY_WITH_RESULT) 设置选择照片以后的跳转地址，默认是返回调用页面
 */
public class PhotoWallActivity extends BaseToolBarActivity implements PhotoWallAdapter.OnSelectImageListener, View.OnClickListener {
    //选择图片路径
    private ArrayList<String> imagePathList;
    //图片墙gridView
    private GridView mPhotoWallGridView;
    //
    private PhotoWallAdapter adapter;
    //确认按钮
    private MenuItem mConfirmItem;
    private int maxSelectCount = 1;
    private final int MAX_LATEST_IMAGE_COUNT = 100;
    //当前文件夹路径
    private String currentFolder = null;
    //当前展示的是否为最近照片
    private boolean isLatest = true;
    // 最近相册key
    public final static int KEY_LATEST_ALBUM = 200;
    // 指定相册文件夹key
    public final static int KEY_FOLDER_ALBUM = 100;
    // 照片选择结果key
    public final static String IMAGE_SELECT_RESULT = "paths";
    //初始化选择图片列表
    private List<String> initSelectList;
    //拍照
    private TextView mTakePhotoButton;

    private final static int TAKE_PIC = 124;
    private Uri mTakePhotoUri;
    //下一页
    private String nextActivity = "";

    /**
     * 获取请求带过来的参数
     */
    public void initIntentData() {
        //最多选择图片数量
        maxSelectCount = getIntent().getIntExtra(PublishParams.MAX_SELECT_COUNT, 1);
        //默认选择图片列表
        initSelectList = getIntent().getStringArrayListExtra(PublishParams.HAS_SELECT_LIST);

        nextActivity = this.getIntent().getStringExtra(PublishParams.NEXT_ACTIVITY_WITH_RESULT);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_wall);
        setTitle(R.string.latest_image);
        initIntentData();
        mPhotoWallGridView = (GridView) findViewById(R.id.photo_wall_grid);
        //获取最近照片列表
        imagePathList = getLatestImagePaths(MAX_LATEST_IMAGE_COUNT);
        adapter = new PhotoWallAdapter(this, imagePathList, initSelectList, maxSelectCount, this);
        mPhotoWallGridView.setAdapter(adapter);
        mTakePhotoButton = (TextView) findViewById(R.id.take_photo_btn);
        //选择相册监听
        findViewById(R.id.photo_select_album).setOnClickListener(this);
        initTakePhoneListener();

    }

    /**
     * 初始化拍照监听
     */
    public void initTakePhoneListener() {
        if (Utils.getPhoneModel().toLowerCase().indexOf("htc") == -1) {
            mTakePhotoButton.setVisibility(View.VISIBLE);
            mTakePhotoButton.setOnClickListener(this);
        } else {
            mTakePhotoButton.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.take_photo_btn:
                    takePhoto();
                    break;
                case R.id.photo_select_album://跳转到选择相册页面
                {
                    selectPhoto();
                }
                break;
            }
        } catch (Throwable e) {
            ReduceLog.e(e);
        }
    }

    /**
     * 选择相册列表
     */
    public void selectPhoto() {
        Intent intent = new Intent(this, PhotoAlbumActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        if (imagePathList != null && imagePathList.size() > 0) {
            intent.putExtra("latest_count", imagePathList.size());
            intent.putExtra("latest_first_img", imagePathList.get(0));
        }
        startActivity(intent);
        //动画
        overridePendingTransition(R.anim.in_from_bottom, R.anim.out_from_top);
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        try {
            //执行拍照前，应该先判断SD卡是否存在
            String SDState = Environment.getExternalStorageState();
            if (isSdExist()) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //存储目录
                String savePath = ImageSaveUtil.getImageSavePath(this);
                //文件名称
                String avatarName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + ".jpg";
                mTakePhotoUri = Uri.fromFile(new File(savePath, avatarName));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);//将拍取的照片保存到指定URI
                startActivityForResult(intent, TAKE_PIC);
            } else {
                Toast.makeText(this, R.string.sd_not_found, Toast.LENGTH_LONG).show();
            }
        } catch (Throwable e) {
            ReduceLog.e(e);
        }
    }

    /**
     * 判断sd卡是否存在
     *
     * @return
     */
    public Boolean isSdExist() {
        String SDState = Environment.getExternalStorageState();
        return SDState.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        try {
            super.onSaveInstanceState(outState);
            outState.putString("filePath", mTakePhotoUri.getPath());
        } catch (Throwable e) {
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        try {
            super.onRestoreInstanceState(savedInstanceState);
            if (mTakePhotoUri == null) {
                mTakePhotoUri = Uri.fromFile(new File(savedInstanceState.getString("filePath")));
            }
        } catch (Throwable e) {
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PIC:
                if (resultCode == RESULT_OK) {
                    if (mTakePhotoUri == null) {
                        return;
                    }
                    Uri newUri = mTakePhotoUri;
                    mTakePhotoUri = null;
                    String path = null;
                    try {
                        path = newUri.getPath();

                        if (path == null) {
                            return;
                        }
                        // Boolean isReplace = ImageCompressUtil.resetDegreeImage(path, path);
                        //判断拦截END
                        if (!TextUtils.isEmpty(path)) {
                            imagePathList.add(0, path);
                            adapter.selectItem(path);
                        }
                    } catch (Throwable e) {
                        ReduceLog.e(e);
                    }
                    try {
                        //创建文件以后需要广播否则在某些情况下看不到图片，在系统相册也看不到图片
                        if (newUri != null) {
                            // Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri);
                            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path)));
                            sendBroadcast(localIntent);

                        }
                    } catch (Throwable e) {
                        ReduceLog.e(e);
                    }


                } else if (resultCode == RESULT_CANCELED) {
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 完成按钮菜单
     *
     * @param
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_confirm, menu);
        mConfirmItem = menu.findItem(R.id.action_confirm);
        if (maxSelectCount > 1) {
            int initCount = 0;
            if (initSelectList != null) {
                initCount = initSelectList.size();
            }
            if (initCount > 0) {
                mConfirmItem.setEnabled(true);
            } else {
                mConfirmItem.setEnabled(false);
            }
            mConfirmItem.setTitle(getString(R.string.action_complete) + "(" + initCount + "/" + maxSelectCount + ")");
        }
        return true;
    }

    /**
     * 点击完成按钮
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_confirm) { //完成
            completeSelect();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initWidget() {

    }

    @Override
    public void initListener() {

    }

    public void completeSelect() {
        ArrayList<String> paths = getSelectImagePaths();
        if (nextActivity != null)
            forwardNext();
        else
            returnResult();

        ReduceApplication.getInstance().finishActivity(PhotoAlbumActivity.class);
        ReduceApplication.getInstance().finishActivity(PhotoWallActivity.class);

    }

    public void forwardNext() {
        ArrayList<String> paths = getSelectImagePaths();
        Intent intent = null;
        try {
            intent = new Intent(this, Class.forName(nextActivity));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        intent.putStringArrayListExtra(IMAGE_SELECT_RESULT, paths);
        startActivity(intent);

    }

    public void returnResult() {
        ArrayList<String> paths = getSelectImagePaths();
        Intent intent = new Intent();
        intent.putStringArrayListExtra(IMAGE_SELECT_RESULT, paths);
        this.setResult(RESULT_OK, intent);
    }


    @Override
    public void onBackPressed() {
        try {
            String exitDirect = getIntent().getStringExtra(PublishParams.EXIT_ACTIVITY_NAME);
            if (!TextUtils.isEmpty(exitDirect)) {
                ReduceApplication.getInstance().finishActivity(Class.forName(exitDirect));
            }
        } catch (Throwable e) {
            ReduceLog.e(e);
        }
        ReduceApplication.getInstance().finishActivity(PhotoAlbumActivity.class);
        ReduceApplication.getInstance().finishActivity(PhotoWallActivity.class);
    }

    /**
     * 根据图片所属文件夹路径，刷新页面
     */
    private void updateView(int code, String folderPath) {
        imagePathList.clear();
        adapter.notifyDataSetChanged();

        if (code == KEY_FOLDER_ALBUM) {   //某个相册文件夹
            int lastSeparator = folderPath.lastIndexOf(File.separator);
            String folderName = folderPath.substring(lastSeparator + 1);
            setTitle(folderName);
            ArrayList<String> imagePaths = getAllImagePathsByFolder(folderPath);
            if (imagePaths != null && imagePathList != null) {
                imagePathList.addAll(imagePaths);
            }

            String feelPath = ImageSaveUtil.getImageSavePath(this);
            if (feelPath != null && feelPath.equals(folderPath)) {
                mTakePhotoButton.setVisibility(View.VISIBLE);
            } else {
                mTakePhotoButton.setVisibility(View.INVISIBLE);
            }
        } else if (code == KEY_LATEST_ALBUM) {  //最近照片
            setTitle(R.string.latest_image);
            ArrayList<String> imagePaths = getLatestImagePaths(MAX_LATEST_IMAGE_COUNT);
            if (imagePaths != null && imagePathList != null) {
                imagePathList.addAll(imagePaths);
            }

            mTakePhotoButton.setVisibility(View.VISIBLE);
        }

        adapter.notifyDataSetChanged();
        if (imagePathList.size() > 0) {
            //滚动至顶部
            mPhotoWallGridView.smoothScrollToPosition(0);
        }
    }


    /**
     * 获取指定路径下的所有图片文件。
     */
    private ArrayList<String> getAllImagePathsByFolder(String folderPath) {
        File folder = new File(folderPath);
        String[] allFileNames = folder.list();
        if (allFileNames == null || allFileNames.length == 0) {
            return null;
        }

        ArrayList<String> imageFilePaths = new ArrayList<String>();
        for (int i = allFileNames.length - 1; i >= 0; i--) {
            if (Utils.isImage(allFileNames[i])) {
                imageFilePaths.add(folderPath + File.separator + allFileNames[i]);
            }
        }

        return imageFilePaths;
    }

    /**
     * 使用ContentProvider读取SD卡最近图片。
     */
    private ArrayList<String> getLatestImagePaths(int maxCount) {
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String key_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
        String key_DATA = MediaStore.Images.Media.DATA;

        ContentResolver mContentResolver = getContentResolver();

        // 只查询jpg和png的图片,按最新修改排序
        Cursor cursor = mContentResolver.query(mImageUri, new String[]{key_DATA},
                key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=?",
                new String[]{"image/jpg", "image/jpeg", "image/png"},
                MediaStore.Images.Media.DATE_MODIFIED);

        ArrayList<String> latestImagePaths = null;
        if (cursor != null) {
            //从最新的图片开始读取.
            //当cursor中没有数据时，cursor.moveToLast()将返回false
            if (cursor.moveToLast()) {
                latestImagePaths = new ArrayList<String>();

                while (true) {
                    // 获取图片的路径
                    String path = cursor.getString(0);
                    latestImagePaths.add(path);

                    if (latestImagePaths.size() >= maxCount || !cursor.moveToPrevious()) {
                        break;
                    }
                }
            }
            cursor.close();
        }

        return latestImagePaths;
    }

    /**
     * 获取已选择的图片路径
     *
     * @return
     */
    private ArrayList<String> getSelectImagePaths() {
        List<String> selectList = adapter.getSelectionList();
        if (selectList.size() == 0) {
            return null;
        }
        ArrayList<String> selectedImageList = new ArrayList<String>();
        selectedImageList.addAll(selectList);
        return selectedImageList;
    }


    @Override
    public Boolean beforeSelectImage(String filePath, int selectCount) {
        if (selectCount >= maxSelectCount) {
            String maxStr = getString(R.string.max_select_pic_count);
            maxStr = String.format(maxStr, maxSelectCount);
            Utils.showToast(this, maxStr);
            return false;
        }
        return true;

    }

    @Override
    public void onSelectImage(String filePath, int selectCount) {
        if (maxSelectCount == 1) {
            completeSelect();
        }
        if (mConfirmItem != null) {
            mConfirmItem.setEnabled(true);
            mConfirmItem.setTitle(getString(R.string.action_complete) + "(" + selectCount + "/" + maxSelectCount + ")");
        }
    }

    @Override
    public void cancelSelectImage(String filePath, int selectCount) {
        if (selectCount == 0) {
            mConfirmItem.setEnabled(false);
        }
        if (mConfirmItem != null) {
            mConfirmItem.setTitle(getString(R.string.action_complete) + "(" + selectCount + "/" + maxSelectCount + ")");
        }
    }

    /**
     * 从相册页面跳转至此页
     *
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //动画
        overridePendingTransition(R.anim.in_from_top, R.anim.out_from_bottom);

        int code = intent.getIntExtra("code", -1);
        if (KEY_FOLDER_ALBUM == code) {//某个相册
            String folderPath = intent.getStringExtra("folderPath");
            if (isLatest || (folderPath != null && !folderPath.equals(currentFolder))) {
                currentFolder = folderPath;
                updateView(KEY_FOLDER_ALBUM, currentFolder);
                isLatest = false;
            }
        } else if (code == KEY_LATEST_ALBUM) {//“最近照片”
            if (!isLatest) {
                updateView(KEY_LATEST_ALBUM, null);
                isLatest = true;
            }
        }
    }


}
